package com.sport.controller;

import com.sport.utils.RedisUtil;
import com.sport.utils.Result;
import com.sport.service.SysUserService;
import com.sport.utils.SecurityUtil;
import com.sport.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

@RestController
@RequestMapping("/user")
@Api(tags = "用户使用接口")
public class LoginController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    RedisUtil redisUtil;
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        return sysUserService.login(loginVo);
    }
    @ApiOperation(value = "获取用户基本信息")
    @GetMapping("/getInfo")
    public Result getUserInfo(Principal principal){

        if(null==principal){
            return Result.fail("请登录");
        }
        return Result.success("获取用户信息成功", SecurityUtil.getUser());
    }

    @ApiOperation(value = "用户退出登录")
    @GetMapping("logout")
    public Result logout(){
        redisUtil.delKey("userInfo_"+SecurityUtil.getUsername());
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication!=null){
            SecurityContextHolder.getContext().setAuthentication(null);
        }

        return Result.success("退出成功");
    }

}
